package cn.itzzx.lagou.minicat.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
public class StaticResourceUtil {

    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        int resourceSize = count;

        //http请求头输出,然后在输出具体内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //读取内容输出
        long written = 0; //已经读取的内容长度
        int byteSize = 1024; //计划每次缓冲的长度
        byte[] bytes = new byte[byteSize];

        //如果 written < resourceSize 表示文件还没有写完
        while (written < resourceSize) {
            // 说明剩余的读取大小不足一个1024长度，那就按真实的长度处理，输出空的话就不合适
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written); //剩余的文件内容长度
                bytes = new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            //每处理一次就需要 + byteSize
            written += byteSize;
        }

    }
}
